package com.szh.zx.javacorecorret.chap3.two;
// 章节 3.2
// 类 Phaser 是 对 CyclicBarrier 类的增强，Phaser对计数是加法操作。单词 Phaser 是移相器

import java.util.concurrent.Phaser;

public class PhaserTest {
	public static void main(String[] args) {
		Phaser phaser = new Phaser(3);
		PrintTools.phaser = phaser;

		ThreadA threadA = new ThreadA(phaser);
		threadA.setName("A");
		threadA.start();

		ThreadB threadB = new ThreadB(phaser);
		threadB.setName("B");
		threadB.start();

		ThreadC threadC = new ThreadC(phaser);
		threadC.setName("C");
		threadC.start();
		System.out.println("主线程结束");
	}
}
class ThreadA extends Thread{
	private Phaser phaser;

	@Override
	public void run() {
		PrintTools.methodA();
	}

	public ThreadA(Phaser phaser) {
		this.phaser = phaser;
	}

}
class ThreadB extends Thread{
	private Phaser phaser;

	@Override
	public void run() {
		PrintTools.methodA();
	}

	public ThreadB(Phaser phaser) {
		this.phaser = phaser;
	}

}
class ThreadC extends Thread{
	private Phaser phaser;

	@Override
	public void run() {
		PrintTools.methodB();
	}

	public ThreadC(Phaser phaser) {
		this.phaser = phaser;
	}

}
class PrintTools{
	public static Phaser phaser;
	public static void methodA(){
		System.out.println(Thread.currentThread().getName()+" A1 begin ="+System.currentTimeMillis());
		// 到达 等待 促进。 这个方法的作用 是当线程到达 屏障，在此等待一段时间，等到条件满足后继续向下一个屏障继续执行
		phaser.arriveAndAwaitAdvance();
		System.out.println(Thread.currentThread().getName()+" A1 end ="+System.currentTimeMillis());

		System.out.println(Thread.currentThread().getName()+" A2 begin ="+System.currentTimeMillis());
		phaser.arriveAndAwaitAdvance();
		System.out.println(Thread.currentThread().getName()+" A2 end ="+System.currentTimeMillis());

	}

	public static void methodB(){
		try {
			System.out.println(Thread.currentThread().getName()+" A1 begin ="+System.currentTimeMillis());
			Thread.sleep(5000);
			phaser.arriveAndAwaitAdvance();
			System.out.println(Thread.currentThread().getName()+" A1 end ="+System.currentTimeMillis());

			System.out.println(Thread.currentThread().getName()+" A2 begin ="+System.currentTimeMillis());
			Thread.sleep(5000);
			phaser.arriveAndAwaitAdvance();
			System.out.println(Thread.currentThread().getName()+" A2 end ="+System.currentTimeMillis());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

